package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.SetmealCheckGroupDao;
import com.itheima.health.dao.SetmealDao;
import com.itheima.health.pojo.dto.QueryPageBeanDTO;
import com.itheima.health.pojo.entity.Setmeal;
import com.itheima.health.pojo.entity.SetmealCheckGroup;
import com.itheima.health.pojo.result.PageResult;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private SetmealCheckGroupDao setmealCheckGroupDao;
    @Override
    public PageResult findPage(QueryPageBeanDTO queryDto) {
        PageHelper.startPage(queryDto.getCurrentPage(), queryDto.getPageSize());
        Page<Setmeal> setmealList = setmealDao.selectByConditon(queryDto.getQueryString());
        return new PageResult(setmealList.getTotal(), setmealList.getResult());
    }

    @Transactional
    @Override
    public void add(List<Integer> ids, Setmeal setmeal) {
        //参数校验在控制层用validated做过了

        //todo code和name不能和数据库的数据重复

        //插入setmeal
        setmealDao.insert(setmeal);
        Integer setmealId = setmeal.getId();
        if (ids.isEmpty()) return;

        //插入sermeal_ckeckgroup
        List<SetmealCheckGroup> collect = ids.stream().map(checkgroupId -> new SetmealCheckGroup(setmealId, checkgroupId)).collect(Collectors.toList());
        setmealCheckGroupDao.insertBatch(collect);

    }
}
